package cn.labbook.bluetooth.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.util.JdbcUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.*;

/**
 * Created by Administrator on 2017/10/12.
 */
@Component
public class DbUtils {

    private static DruidDataSource dataSource;

    public DruidDataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DruidDataSource dataSource) {
        DbUtils.dataSource = dataSource;
    }

    public static void execute(String sql, Object... params) throws SQLException {
        JdbcUtils.execute(dataSource, sql, params);
    }

    public static <T> List<T> query(Class<T> tClass, String sql, Object... params) throws SQLException {

        List<Map<String, Object>> maps = JdbcUtils.executeQuery(dataSource, sql, params);
        List<T> list = new ArrayList<>();

        maps.forEach((Map<String, Object> m) -> {
            T t = mapToBean(tClass, m);
            list.add(t);
        });

        return list;
    }

    public static List<Map<String, Object>> query(String sql, Object... params) throws SQLException {

        List<Map<String, Object>> maps = JdbcUtils.executeQuery(dataSource, sql, params);
        return maps;
    }

    private static <T> T mapToBean(Class<T> tClass, Map<String, Object> map) {

        T t = null;
        try {

            t = tClass.newInstance();

            Set<Map.Entry<String, Object>> entries = map.entrySet();

            Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> next = iterator.next();
                Field field = tClass.getDeclaredField(DbStringConvert(next.getKey()));
                if (field != null) {
                    field.setAccessible(true);
                    Object value = next.getValue();
                    if (value instanceof Long)
                        value = ((Long) value).intValue();
                    field.set(t, value);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    public static String DbStringConvert(String dbString) {

        char[] chars = dbString.toCharArray();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] != '_') {
                sb.append(chars[i]);
            } else {
                sb.append(String.valueOf(chars[++i]).toUpperCase());
            }
        }

        return sb.toString();
    }


}
